/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EnvioReencauche.java
 *
 * Created on 15-jun-2012, 13:28:45
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.*;
import com.camachosanchez.controler.jdbc.NeumaticosJdbcControler;
import com.camachosanchez.controler.jpa.DistribuidoresNeumaticosJpaController;
import com.camachosanchez.gui.table.ModeloTablaMontajeDesmontaje;
import com.camachosanchez.gui.table.RenderizadorTablaReencauche;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.awt.Component;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author Rolando
 */
public class EnvioReencauche extends javax.swing.JDialog {

    private EntityManagerFactory emf = null;
    private ModeloTablaMontajeDesmontaje modelo;
    private List<Neumaticos> neumaticos;
    private TableSorter tableSorter;
    private TableFilterHeader filterHeader;
    private RenderizadorTablaReencauche render;

    /** Creates new form EnvioReencauche */
    public EnvioReencauche(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.emf = JPAUtil.getEntityManagerFactory();
        dateFecha.setDate(new Date());
        tablaLlantas.setDragEnabled(true);
        NeumaticosJdbcControler daoJdbc = new NeumaticosJdbcControler();
        neumaticos = daoJdbc.findNeumaticosParaReencauche();
        DistribuidoresNeumaticosJpaController dist = new DistribuidoresNeumaticosJpaController(null);
        List<DistribuidoresNeumaticos> distribuidores = dist.findDistribuidoresNeumaticosEntities();
        if (distribuidores != null) {
            comboDistribuidores.setModel(new DefaultComboBoxModel(distribuidores.toArray()));
        }
        modelo = new ModeloTablaMontajeDesmontaje();
        render = new RenderizadorTablaReencauche();
        tablaLlantas.setDefaultRenderer(String.class, render);
        drop.setDialogo(this);
        tableSorter = new TableSorter(modelo, tablaLlantas.getTableHeader());
        tablaLlantas.setModel(tableSorter);
        filterHeader = new TableFilterHeader();
        filterHeader.setTable(tablaLlantas);
        llenarTabla("");
        tablaLlantas.getTableHeader().setReorderingAllowed(false);
        this.setSize(950, 500);
        this.setLocationRelativeTo(null);
        GUIUtil.addEscapeKey(this);
        MaxLengthTextDocument docNumGuia = new MaxLengthTextDocument();
        MaxLengthTextDocument docTelefono = new MaxLengthTextDocument();
        MaxLengthTextDocument docDireccion = new MaxLengthTextDocument();
        docNumGuia.setMaxChars(40, Constantes.ANY);
        docTelefono.setMaxChars(20, Constantes.ANY);
        docDireccion.setMaxChars(40, Constantes.ANY);
        txtNroGuia.setDocument(docNumGuia);
        txtDireccion.setDocument(docDireccion);
        txtTelefono.setDocument(docTelefono);
        actualizarCombo();
    }

    private void llenarTabla(String filtro) {
        modelo.limpiar();
        try {
            for (Neumaticos neumatico : neumaticos) {
                if (neumatico.getCodigo().toUpperCase().contains(filtro.toUpperCase()) && !agregado(neumatico)) {
                    modelo.agregarNeumatico(neumatico, -1);
                }
            }
            GUIUtil.SetAnchoColumnas(tablaLlantas);
            setColumnasOcultas();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setColumnasOcultas() {
        tablaLlantas.getColumnModel().getColumn(4).setMinWidth(0);
        tablaLlantas.getColumnModel().getColumn(4).setMaxWidth(0);
        tablaLlantas.getColumnModel().getColumn(4).setPreferredWidth(0);
    }

    public void agregarLlanta(int id) {
        PanelLlantaReencauche panel = new PanelLlantaReencauche(this, id);
        contenedor.add(panel);
        contenedor.updateUI();
        int height = (int) contenedor.getPreferredSize().getHeight();
        Rectangle rect = new Rectangle(0, height, 10, 10);
        contenedor.scrollRectToVisible(rect);
        jScrollPane1.updateUI();
        modelo.eliminarLlanta(id);
        tablaLlantas.updateUI();
        jLabel8.setText("Cantidad de neumáticos: " + (contenedor.getComponents().length - 1));
    }

    public void borrarLlanta(int id) {
        NeumaticosJdbcControler dao = new NeumaticosJdbcControler();
        this.modelo.agregarNeumatico(dao.findNeumatico(id), 0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jPanel8 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaLlantas = new javax.swing.JTable();
        jLabel8 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        drop = new com.camachosanchez.gui.PanelAgregarNeumaticoReencauche();
        jPanel5 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNroGuia = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        dateFecha = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        comboDistribuidores = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        contenedor = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Envío de Neumáticos a Reencauche ::.");
        setResizable(false);

        jToolBar1.setBackground(new java.awt.Color(204, 204, 255));
        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setOpaque(false);

        jPanel8.setBackground(new java.awt.Color(255, 255, 255));
        jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_new.png"))); // NOI18N
        btnNuevo.setToolTipText("Nuevo");
        btnNuevo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnNuevo.setFocusable(false);
        btnNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevo.setMaximumSize(new java.awt.Dimension(22, 22));
        btnNuevo.setMinimumSize(new java.awt.Dimension(22, 22));
        btnNuevo.setPreferredSize(new java.awt.Dimension(22, 22));
        btnNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });
        jPanel8.add(btnNuevo);

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        jPanel8.add(btnGuardar);

        jToolBar1.add(jPanel8);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 10));
        jPanel1.setMinimumSize(new java.awt.Dimension(300, 49));
        jPanel1.setPreferredSize(new java.awt.Dimension(500, 428));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jLabel2.setText("NEUMÁTICOS DISPONIBLES");
        jLabel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 1, 5, 1));
        jPanel1.add(jLabel2, java.awt.BorderLayout.PAGE_START);

        tablaLlantas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaLlantas.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tablaLlantas.setRowHeight(22);
        tablaLlantas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tablaLlantas);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jLabel8.setText("Cantidad de neumáticos:");
        jLabel8.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 10, 5, 1));
        getContentPane().add(jLabel8, java.awt.BorderLayout.PAGE_END);

        jPanel3.setPreferredSize(new java.awt.Dimension(660, 467));

        javax.swing.GroupLayout dropLayout = new javax.swing.GroupLayout(drop);
        drop.setLayout(dropLayout);
        dropLayout.setHorizontalGroup(
            dropLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 640, Short.MAX_VALUE)
        );
        dropLayout.setVerticalGroup(
            dropLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos generales", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); // NOI18N
        jPanel5.setOpaque(false);

        jLabel1.setText("<html>Nº de Guía:<font color='red'>(*)</font></html>");

        txtNroGuia.setMinimumSize(new java.awt.Dimension(120, 20));
        txtNroGuia.setPreferredSize(new java.awt.Dimension(120, 20));

        jLabel4.setText("Fecha:");
        jLabel4.setPreferredSize(new java.awt.Dimension(46, 14));

        dateFecha.setDateFormatString("dd/MM/yyyy");
        dateFecha.setMaxSelectableDate(new Date());
        dateFecha.setMinimumSize(new java.awt.Dimension(87, 20));

        jLabel5.setText("Distribuidor:");

        comboDistribuidores.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboDistribuidores.setPreferredSize(new java.awt.Dimension(160, 20));
        comboDistribuidores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboDistribuidoresActionPerformed(evt);
            }
        });

        jLabel7.setText("Dirección:");
        jLabel7.setPreferredSize(new java.awt.Dimension(69, 14));

        txtDireccion.setPreferredSize(new java.awt.Dimension(150, 20));

        jLabel6.setText("Teléfono:");
        jLabel6.setPreferredSize(new java.awt.Dimension(58, 14));

        txtTelefono.setPreferredSize(new java.awt.Dimension(120, 20));

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addComponent(txtNroGuia, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(comboDistribuidores, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTelefono, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
                    .addComponent(txtDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtNroGuia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(comboDistribuidores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 17, Short.MAX_VALUE))
                .addContainerGap())
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        contenedor.setBackground(new java.awt.Color(255, 255, 255));
        contenedor.setBorder(javax.swing.BorderFactory.createEmptyBorder(3, 1, 3, 1));
        contenedor.setLayout(new javax.swing.BoxLayout(contenedor, javax.swing.BoxLayout.Y_AXIS));

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));
        jPanel7.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jPanel7.setMaximumSize(new java.awt.Dimension(2147483647, 21));
        jPanel7.setLayout(new java.awt.BorderLayout(4, 0));

        jLabel13.setBackground(new java.awt.Color(255, 255, 255));
        jLabel13.setMaximumSize(new java.awt.Dimension(19, 21));
        jLabel13.setMinimumSize(new java.awt.Dimension(19, 21));
        jLabel13.setOpaque(true);
        jLabel13.setPreferredSize(new java.awt.Dimension(19, 21));
        jPanel7.add(jLabel13, java.awt.BorderLayout.LINE_START);

        jPanel6.setBackground(new java.awt.Color(255, 255, 255));
        jPanel6.setMaximumSize(new java.awt.Dimension(430, 20));
        jPanel6.setPreferredSize(new java.awt.Dimension(424, 53));
        jPanel6.setLayout(new java.awt.GridLayout(1, 4, 4, 0));

        jLabel9.setBackground(new java.awt.Color(255, 204, 102));
        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel9.setText("CÓDIGO");
        jLabel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel9.setOpaque(true);
        jPanel6.add(jLabel9);

        jLabel10.setBackground(new java.awt.Color(255, 204, 102));
        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel10.setText("BANDA (ACTUAL)");
        jLabel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel10.setOpaque(true);
        jPanel6.add(jLabel10);

        jLabel14.setBackground(new java.awt.Color(255, 204, 102));
        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel14.setText("PISO (ACTUAL)");
        jLabel14.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel14.setOpaque(true);
        jPanel6.add(jLabel14);

        jLabel11.setBackground(new java.awt.Color(255, 204, 102));
        jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel11.setText("NUEVA BANDA");
        jLabel11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel11.setOpaque(true);
        jPanel6.add(jLabel11);

        jLabel15.setBackground(new java.awt.Color(255, 204, 102));
        jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel15.setText("NUEVO PISO");
        jLabel15.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel15.setOpaque(true);
        jPanel6.add(jLabel15);

        jLabel12.setBackground(new java.awt.Color(255, 204, 102));
        jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel12.setText("PRECIO");
        jLabel12.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel12.setOpaque(true);
        jPanel6.add(jLabel12);

        jLabel16.setBackground(new java.awt.Color(255, 204, 102));
        jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel16.setText("GARANTÍA");
        jLabel16.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 0)));
        jLabel16.setOpaque(true);
        jPanel6.add(jLabel16);

        jPanel7.add(jPanel6, java.awt.BorderLayout.CENTER);

        contenedor.add(jPanel7);

        jScrollPane1.setViewportView(contenedor);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                    .addComponent(drop, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(drop, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel3, java.awt.BorderLayout.WEST);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void comboDistribuidoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboDistribuidoresActionPerformed
// TODO add your handling code here:
    actualizarCombo();
}//GEN-LAST:event_comboDistribuidoresActionPerformed

private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
// TODO add your handling code here:
    guardar();
}//GEN-LAST:event_btnGuardarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        GUIUtil.limpiarVentana(this.getRootPane().getComponents());
        int tam = contenedor.getComponentCount();
        Component[] componentes = contenedor.getComponents();
        for (int i = 0; i < tam; i++) {
            if (componentes[i] instanceof PanelLlantaReencauche) {
                this.eliminar((PanelLlantaReencauche) componentes[i]);
                this.borrarLlanta(((PanelLlantaReencauche) componentes[i]).getId_llanta());
            }
        }
    }//GEN-LAST:event_btnNuevoActionPerformed
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(EnvioReencauche.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(EnvioReencauche.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(EnvioReencauche.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(EnvioReencauche.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the dialog */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                EnvioReencauche dialog = new EnvioReencauche(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JComboBox comboDistribuidores;
    private javax.swing.JPanel contenedor;
    private com.toedter.calendar.JDateChooser dateFecha;
    private com.camachosanchez.gui.PanelAgregarNeumaticoReencauche drop;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tablaLlantas;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtNroGuia;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables

    private void actualizarCombo() {
        DistribuidoresNeumaticos seleccionado = (DistribuidoresNeumaticos) comboDistribuidores.getSelectedItem();
        if (seleccionado != null) {
            txtTelefono.setText(seleccionado.getTelefono());
            txtDireccion.setText(seleccionado.getDireccion());
        }
    }

    private void guardar() {
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            ControlReencauche control = new ControlReencauche();
            String guia_remision = txtNroGuia.getText().trim();
            if (!guia_remision.isEmpty()) {
                DistribuidoresNeumaticos dist = (DistribuidoresNeumaticos) comboDistribuidores.getSelectedItem();
                if (dist == null) {
                    JOptionPane.showMessageDialog(this, "Se requiere un distribuidor de neumático para envío a reencauche. Si no existe uno agréguelo desde el menú Logística.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
                    comboDistribuidores.requestFocusInWindow();
                    return;
                }
                control.setNumGuiaRemision(guia_remision);
                control.setFechaEnvio(dateFecha.getDate());
                control.setIdDistribuidorNeumaticos(dist);
                control.setTelefono(txtTelefono.getText().trim());
                control.setDireccion(txtDireccion.getText().trim());
                control.setEstadoTransaccion(false); //Operación incompleta
                control.setEstado(true); //Visible
                control.setIdUsuario(Constantes.currentUser);
                control.setFechaInsercionActualizacion(new Date());
                List<DetalleControlReencauche> detalles = new ArrayList<DetalleControlReencauche>();
                //Detalles
                Component comp[] = contenedor.getComponents();
                if (comp.length > 1) {
                    for (int i = 1; i < comp.length; i++) {
                        Component component = comp[i];
                        if (component instanceof PanelLlantaReencauche) {
                            PanelLlantaReencauche detalle = (PanelLlantaReencauche) component;
                            DetalleControlReencauche item = detalle.guardar();
                            if (item != null) {
                                detalles.add(item);
                            }
                        }
                    }

                    Categorias categoriaReencauche = new Categorias(Constantes.CATEGORIA_REENCAUCHE);
                    for (DetalleControlReencauche detalle : detalles) {
                        detalle.setIdControlReencauche(control);
                        //Marcamos el neumático como enviado a reencauche
                        int id_neumatico = detalle.getIdNeumatico().getId();
                        Neumaticos temp = (Neumaticos) em.getReference(Neumaticos.class, id_neumatico);
                        temp.setIdCategoria(categoriaReencauche);
                    }
                    control.setDetalleControlReencaucheList(detalles);
                    em.persist(control);
                    tx.commit();
                    JOptionPane.showMessageDialog(this, "El registro se ha completado exitosamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else { //Se necesita al menos un detalle
                    JOptionPane.showMessageDialog(this, "Se debe registrar al menos un envío a reencauche para completar la operación.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(this, "Se requiere el número de guía de remisión.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
                txtNroGuia.requestFocusInWindow();
                return;
            }
        } catch (Exception e) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void eliminar(PanelLlantaReencauche aThis) {
        contenedor.remove(aThis);
        contenedor.updateUI();
        jLabel8.setText("Cantidad de neumáticos: " + (contenedor.getComponents().length - 1));
    }

    private boolean agregado(Neumaticos neumatico) {
        Component comp[] = contenedor.getComponents();
        for (int i = 0; i < comp.length; i++) {
            Component component = comp[i];
            if (component instanceof PanelLlantaReencauche) {
                PanelLlantaReencauche detalle = (PanelLlantaReencauche) component;
                if (detalle.getId_llanta() == neumatico.getId()) {
                    return true;
                }
            }
        }
        return false;
    }
}
